import pageStyles from '@/common/pageLayout.less';
import { CaretRightOutlined, DoubleLeftOutlined, DoubleRightOutlined, EditOutlined } from '@ant-design/icons';
import { Card, Spin, Collapse, Divider, Form, Space, Button, message } from 'antd';
import '../common/styles.less';
import { RuleInfoForm } from './RuleInfoForm';
import { RestsInfoForm } from './RestsInfoForm';
import ScrollBarLayout from '@/components/ScrollBarLayout';
import { useState, useCallback, useMemo } from 'react';
import { DiffOutlined } from '@ant-design/icons';
import Cls from 'classnames';
import { connect, history } from 'umi';
import { RuleManageAPI } from '../common/type';
import { useEffect } from 'react';
import { detailRuleServices, editRuleServices, saveRuleServices } from '../services/UpdateService';
import { getKeyRouter } from '@/utils';
const { Panel } = Collapse;

const UpdateView: React.FC<RuleManageAPI.IDetailViewAPI> = ({ curRes, locationProps }) => {
  /**
   * 样式
   * */
  const prefixCls = 'rule-update-';

  /**
   * 保存归口部门公司id
   * */
  const [dutyId, setDutyId] = useState<Record<string, any>>({
    dutyDepartmentID: null,
    dutyCompanyID: null,
  });

  /**
   * 表单 form
   */
  const [updateForm] = Form.useForm();

  /**
   * 结构路由传参
   * */
  const {
    state: { title, recordObj },
  } = locationProps;

  /**
   * 详情对象
   * */
  const [detailObj, setDetailObj] = useState({});

  /**
   * 详情回调callback
   * */
  const detailRuleCallback = (res: Record<string, any>) => {
    if (res?.msgFlag) {
      message?.success(res?.msg);
      // form表单
      updateForm.setFieldsValue(res?.obj);
      // 保存一下归口id
      setDutyId({
        dutyDepartmentID: res?.obj?.dutyDepartmentID,
        dutyCompanyID: res?.obj?.dutyCompanyID,
      });
      // 保存详情对象
      setDetailObj(res?.obj);
    }
  };

  /**
   * 编辑接口回调
   * */
  const editRuleCallback = (res: Record<string, any>) => {
    if (res?.msgFlag) {
      message?.success(res?.msg);
      detailRuleRun({ id: recordObj?.id });
    }
  };

  /**
   * 添加规则callback
   * */
  const saveRuleCallback = (res: Record<string, any>) => {
    if (res?.msgFlag) {
      message.success(res?.msg);
      history.push({
        pathname: `/purchaseRuleController/edit/:${getKeyRouter()}${getKeyRouter()}`,
        state: {
          title: '编辑采购规则',
          recordObj: { ...res?.obj },
          delRouterName: history.location.pathname, //必传,要删除的路由名称
        },
      });
    }
  };

  /**
   * 添加规则services
   * */
  const { saveRuleRun, saveRuleLoading } = saveRuleServices(saveRuleCallback);

  /**
   * 详情接口services
   * */
  const { detailRuleRun, detailRuleLoading } = detailRuleServices(detailRuleCallback);

  /**
   * 编辑接口
   * */
  const { editRuleRun, editRuleLoading } = editRuleServices(editRuleCallback);

  useEffect(() => {
    // 编辑
    if (recordObj?.id) {
      // 详情接口
      detailRuleRun({ id: recordObj?.id });
    }
  }, [recordObj]);

  /**
   * 变更归口id方法
   * */
  const setDutyIdFun = ({ dep, com }: Record<string, any>) => {
    setDutyId({
      dutyDepartmentID: dep,
      dutyCompanyID: com,
    });
  };

  /**
   * 初始化和默认折叠面板key值
   * */
  const activeKeys = ['rule-basicInfo', 'rule-restsInfo'];

  /**
   * 折叠面板的key值
   * */
  const [activeKey, setActiveKey] = useState<Array<string>>(activeKeys);

  /**
   * 切换点击全部展开
   * */
  const changeCollKey = useCallback(
    (keyList: string[]) => {
      setActiveKey(keyList);
    },
    [activeKey],
  );

  /**
   * @collAllRemove
   * @description 折叠面板全选于反选
   * @param clickType 类型
   */
  const collAllRemove = (clickType: string) => {
    if (clickType == 'allOpen') {
      changeCollKey(activeKeys);
    }
    if (clickType == 'allClose') {
      changeCollKey([]);
    }
  };

  /**
   * 全部展开和折叠
   * */
  const extraRender = () => (
    <Space>
      <Button
        type={!activeKey.length ? 'dashed' : 'primary'}
        size={'small'}
        icon={<DoubleLeftOutlined className={`${prefixCls}conmpanyCardExtra`} />}
        className="manageBtntTxtStyle"
        onClick={() => {
          collAllRemove('allClose');
        }}
        disabled={!activeKey.length ? true : false}
      >
        全部折叠
      </Button>
      <Button
        type={activeKey.length ? 'dashed' : 'primary'}
        size={'small'}
        icon={<DoubleRightOutlined className={`${prefixCls}conmpanyCardExtra`} />}
        className="manageBtntTxtStyle"
        onClick={() => {
          collAllRemove('allOpen');
        }}
        disabled={activeKey.length == 3 ? true : false}
      >
        全部展开
      </Button>
    </Space>
  );

  /**
   * 折叠面板改变
   * @param keys 面板KEY
   */
  const onChangeActivekey = (keys: string | string[]) => {
    setActiveKey(Array.isArray(keys) ? keys : [keys]);
  };

  /**
   * 渲染按钮
   * */
  const isShowBtn = useMemo(() => {
    if (recordObj?.id) {
      // 编辑
      if (curRes?.['/purchaseRuleController/edit']) {
        return [
          <Button
            type="primary"
            // icon={<EditOutlined />}
            loading={saveRuleLoading || detailRuleLoading || editRuleLoading}
            onClick={() => {
              updateForm?.validateFields()?.then((res) => {
                editRuleRun({
                  ...detailObj,
                  ...res,
                  ...dutyId,
                });
              });
            }}
          >
            编辑
          </Button>,
        ];
      } else {
        return [];
      }
    } else {
      // 添加
      if (curRes?.['/purchaseStyleRuleController/add']) {
        return [
          <Button
            type="primary"
            // icon={<DiffOutlined />}
            loading={saveRuleLoading || detailRuleLoading || editRuleLoading}
            onClick={() => {
              updateForm?.validateFields()?.then((res) => {
                let obj = {
                  ...res,
                  ...dutyId,
                };
                saveRuleRun(obj);
              });
            }}
          >
            提交
          </Button>,
        ];
      } else {
        return [];
      }
    }
  }, [recordObj, curRes, detailObj, dutyId, saveRuleLoading, detailRuleLoading, editRuleLoading]);

  return (
    <Card
      title={title}
      className={Cls(pageStyles['page-view-cardView'], prefixCls + 'updateCard')}
      bodyStyle={{ padding: '0px' }}
      extra={extraRender()}
      actions={isShowBtn}
    >
      <Spin spinning={saveRuleLoading || detailRuleLoading || editRuleLoading}>
        <ScrollBarLayout>
          <Form form={updateForm}>
            <Collapse
              activeKey={activeKey}
              bordered={false}
              className={prefixCls + 'updateCollapse'}
              expandIconPosition="end"
              onChange={onChangeActivekey}
              expandIcon={({ isActive }) => {
                return <CaretRightOutlined rotate={isActive ? 90 : 0} />;
              }}
            >
              {/* 基本信息 */}
              <Panel header={<Divider orientation="left">{'基本信息'}</Divider>} key={'rule-basicInfo'} id={'rule-basicInfo'}>
                <div
                  className={pageStyles['fromView-styles']}
                  style={{
                    width: '100%',
                    margin: '0 auto',
                    padding: '20px',
                    borderRadius: '10px',
                    overflow: 'hidden',
                  }}
                >
                  <RuleInfoForm setDutyIdFun={setDutyIdFun} />
                </div>
              </Panel>
              {/* 其他信息 */}
              <Panel header={<Divider orientation="left">{'其他信息'}</Divider>} key={'rule-restsInfo'} id={'rule-restsInfo'}>
                <div
                  className={pageStyles['fromView-styles']}
                  style={{
                    width: '100%',
                    margin: '0 auto',
                    padding: '20px',
                    borderRadius: '10px',
                    overflow: 'hidden',
                  }}
                >
                  <RestsInfoForm recordObj={recordObj || {}} />
                </div>
              </Panel>
            </Collapse>
          </Form>
        </ScrollBarLayout>
      </Spin>
    </Card>
  );
};

export default connect(({ baseLogin }: Record<string, any>) => ({
  curRes: baseLogin?.permissions,
}))(UpdateView);
